<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 数据概览卡片 -->
      <el-col :span="8" v-for="(item, index) in statCards" :key="index">
        <el-card class="stat-card" :body-style="{ padding: '20px' }">
          <div class="card-content">
            <div class="icon-container" :style="{ backgroundColor: item.color }">
              <el-icon><component :is="item.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">{{ item.title }}</div>
              <div class="stat-value">{{ item.value }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <!-- 每日预约人数统计图表 -->
      <el-col :span="12">
        <el-card class="chart-card" v-loading="loading.visitChart">
          <template #header>
            <div class="card-header">
              <span>每日预约人数统计</span>
              <el-select v-model="dayRange" placeholder="选择时间范围" @change="fetchDailyReservations">
                <el-option label="最近7天" :value="7" />
                <el-option label="最近14天" :value="14" />
                <el-option label="最近30天" :value="30" />
              </el-select>
            </div>
          </template>
          <div class="chart" ref="visitChart"></div>
        </el-card>
      </el-col>

      <!-- 热门参观日期分析 -->
      <el-col :span="12">
        <el-card class="chart-card" v-loading="loading.exhibitionChart">
          <template #header>
            <div class="card-header">
              <span>热门参观日期分析</span>
              <el-button size="small" @click="fetchExhibitionPopularity">刷新</el-button>
            </div>
          </template>
          <div class="chart" ref="exhibitionChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 用户增长趋势 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card" v-loading="loading.userGrowthChart">
          <template #header>
            <div class="card-header">
              <span>用户增长趋势</span>
              <el-select v-model="monthRange" placeholder="选择时间范围" @change="fetchUserGrowth">
                <el-option label="最近6个月" :value="6" />
                <el-option label="最近12个月" :value="12" />
              </el-select>
            </div>
          </template>
          <div class="chart" ref="userGrowthChart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import * as echarts from 'echarts';
import { Calendar, PictureFilled, User } from '@element-plus/icons-vue';
import { getOverview, getDailyReservations, getUserGrowth, getPopularDates, getMuseumInfo } from '@/api/statistics';
import { ElMessage } from 'element-plus';

// 状态管理
const dayRange = ref(7);
const monthRange = ref(6);
const loading = reactive({
  overview: false,
  visitChart: false,
  exhibitionChart: false,
  userGrowthChart: false
});

// 统计卡片数据
const statCards = reactive([
  { title: '展览总数', value: 0, icon: 'PictureFilled', color: '#409EFF' },
  { title: '预约总数', value: 0, icon: 'Calendar', color: '#67C23A' },
  { title: '用户总数', value: 0, icon: 'User', color: '#E6A23C' }
]);

// 图表Dom引用
const visitChart = ref(null);
const exhibitionChart = ref(null);
const userGrowthChart = ref(null);

// 图表实例
let visitChartInstance = null;
let exhibitionChartInstance = null;
let userGrowthChartInstance = null;

// 获取概览数据
const fetchOverview = async () => {
  loading.overview = true;
  try {
    const res = await getOverview();
    if (res.code === 200 && res.data) {
      statCards[0].value = res.data.exhibitionCount;
      statCards[1].value = res.data.reservationCount;
      statCards[2].value = res.data.userCount;
    } else {
      ElMessage.error('获取概览数据失败');
    }
  } catch (error) {
    console.error('获取概览数据失败', error);
    ElMessage.error('获取概览数据失败');
  } finally {
    loading.overview = false;
  }
};

// 获取每日预约人数统计
const fetchDailyReservations = async () => {
  loading.visitChart = true;
  try {
    const res = await getDailyReservations(dayRange.value);
    if (res.code === 200 && res.data) {
      const { dates, counts } = res.data;
      updateVisitChart(dates, counts);
    } else {
      ElMessage.error('获取每日预约数据失败');
    }
  } catch (error) {
    console.error('获取每日预约数据失败', error);
    ElMessage.error('获取每日预约数据失败');
  } finally {
    loading.visitChart = false;
  }
};

// 获取展览热度
const fetchExhibitionPopularity = async () => {
  loading.exhibitionChart = true;
  try {
    const res = await getPopularDates();
    if (res.code === 200 && res.data) {
      updateExhibitionChart(res.data);
    } else {
      ElMessage.error('获取热门参观日期数据失败');
    }
  } catch (error) {
    console.error('获取热门参观日期数据失败', error);
    ElMessage.error('获取热门参观日期数据失败');
  } finally {
    loading.exhibitionChart = false;
  }
};

// 获取用户增长趋势
const fetchUserGrowth = async () => {
  loading.userGrowthChart = true;
  try {
    const res = await getUserGrowth(monthRange.value);
    if (res.code === 200 && res.data) {
      const { months, counts } = res.data;
      updateUserGrowthChart(months, counts);
    } else {
      ElMessage.error('获取用户增长数据失败');
    }
  } catch (error) {
    console.error('获取用户增长数据失败', error);
    ElMessage.error('获取用户增长数据失败');
  } finally {
    loading.userGrowthChart = false;
  }
};

// 更新每日预约统计图表
const updateVisitChart = (dates, counts) => {
  if (visitChartInstance) {
    visitChartInstance.setOption({
      xAxis: {
        data: dates
      },
      series: [
        {
          data: counts,
          type: 'line',
          smooth: true,
          name: '预约人数',
          areaStyle: {}
        }
      ]
    });
  }
};

// 更新热门参观日期图表
const updateExhibitionChart = (data) => {
  if (exhibitionChartInstance) {
    exhibitionChartInstance.setOption({
      series: [
        {
          data: data,
          type: 'pie',
          radius: '50%',
          name: '热门参观日期'
        }
      ]
    });
  }
};

// 更新用户增长趋势图表
const updateUserGrowthChart = (months, counts) => {
  if (userGrowthChartInstance) {
    userGrowthChartInstance.setOption({
      xAxis: {
        data: months
      },
      series: [
        {
          data: counts,
          type: 'bar',
          name: '新增用户'
        }
      ]
    });
  }
};

// 初始化图表
const initCharts = () => {
  // 初始化每日预约人数统计图表
  visitChartInstance = echarts.init(visitChart.value);
  visitChartInstance.setOption({
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [],
        type: 'line',
        smooth: true,
        name: '预约人数',
        areaStyle: {}
      }
    ]
  });

  // 初始化展览参观热度分析图表
  exhibitionChartInstance = echarts.init(exhibitionChart.value);
  exhibitionChartInstance.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 'bottom'
    },
    series: [
      {
        name: '热门参观日期',
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });
  
  // 初始化用户增长趋势图表
  userGrowthChartInstance = echarts.init(userGrowthChart.value);
  userGrowthChartInstance.setOption({
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [],
        type: 'bar',
        name: '新增用户',
        itemStyle: {
          color: '#E6A23C'
        }
      }
    ]
  });

  // 窗口大小改变时重新绘制图表
  window.addEventListener('resize', () => {
    visitChartInstance.resize();
    exhibitionChartInstance.resize();
    userGrowthChartInstance.resize();
  });
};

onMounted(() => {
  // 等待DOM渲染完成后初始化图表
  setTimeout(() => {
    initCharts();
    // 加载数据
    fetchOverview();
    fetchDailyReservations();
    fetchExhibitionPopularity();
    fetchUserGrowth();
  }, 100);
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;

  .chart-row {
    margin-top: 20px;
  }

  .stat-card {
    margin-bottom: 20px;

    .card-content {
      display: flex;
      align-items: center;

      .icon-container {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 15px;

        .el-icon {
          font-size: 24px;
          color: #fff;
        }
      }

      .stat-info {
        .stat-title {
          font-size: 14px;
          color: #909399;
          margin-bottom: 5px;
        }

        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
        }
      }
    }
  }

  .chart-card {
    height: 400px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart {
      height: 300px;
    }
  }
}
</style> 